package com.hub.netty.server.handler;

import cn.hutool.core.util.StrUtil;
import com.hub.netty.server.config.ChannelMap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import lombok.extern.slf4j.Slf4j;


/**
 * @ author 令狐冲
 * @ date & time 2025/3/11 11:06
 */
@Slf4j
public class TokenHandshakeHandler extends ChannelInboundHandlerAdapter {

    private static final String TOKEN_HEADER_NAME = "Authorization";
    private static final String VALID_TOKEN = "Bearer dGVsbG8=";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            HttpHeaders headers = request.headers();

            // 校验 Token
            String token = headers.get(TOKEN_HEADER_NAME);
            if (!StrUtil.equals(VALID_TOKEN, token)) {
                // 发送错误响应并关闭连接
                ctx.close();
                return;
            }
            log.info("Token 验证成功");
            // 将 Channel 存储起来，以便后续使用
            ChannelMap.putChannel(ctx.channel().id().asLongText(), ctx.channel());
            // 继续处理请求
            ctx.fireChannelRead(msg);
        } else {
            ctx.fireChannelRead(msg);
        }
    }
}
